import java.util.Arrays;

/**
 * 面试题65相关题目：不使用新变量，交换两个变量的值
 */
public class Offer_65_II {
    /**
     * 方法二：基于异或运算
     * <p>
     * <ul>
     * <li>{@code a = a ^ b}</li>
     * <li>{@code b = a ^ b}</li>
     * <li>{@code a = a ^ b}</li>
     * </ul>
     */
    public void swapNumbers(int[] nums) {
        nums[0] = nums[0] ^ nums[1];
        nums[1] = nums[0] ^ nums[1];
        nums[0] = nums[0] ^ nums[1];
    }

    /**
     * 方法一：基于加减法
     * <p>
     * <ul>
     * <li>{@code a = a + b}</li>
     * <li>{@code b = a - b}</li>
     * <li>{@code a = a - b}</li>
     * </ul>
     */
    public void swapNumbers1(int[] nums) {
        nums[0] = nums[0] + nums[1];
        nums[1] = nums[0] - nums[1];
        nums[0] = nums[0] - nums[1];
    }

    public static void main(String[] args) {
        Offer_65_II solution = new Offer_65_II();
        int[] nums = { 1, 2 };
        System.out.println("交换前：" + Arrays.toString(nums));
        solution.swapNumbers(nums);
        System.out.println("交换后：" + Arrays.toString(nums));
    }
}
